# Copyright (c) 2021 Presto Labs Pte. Ltd.
# Author: fengyang

import datetime
import subprocess
import sys
import os
import shutil
import json
from absl import app, flags

FLAGS = flags.FLAGS

def main(argv):
  trading_date_str = FLAGS.trading_date
  assert trading_date_str, '--trading_date must be specified.'
  trading_date = datetime.datetime.strptime(trading_date_str, '%Y%m%d')
  start_date = trading_date - datetime.timedelta(days=5)
  start_date_str = datetime.datetime.strftime(start_date, '%Y%m%d')
  kline_cmd_str = ("bazel-bin/cc/appcoin2/support/feed/interval_feed_tool/kline_feed_generator "
        "--date={date} --start-date={start_date} --out-dir={out_dir} "
        "--out-machine={out_machine} --out-recipe=kline_by_trade "
        "--driver={driver}")
  kline_cmd = kline_cmd_str.format(date=trading_date_str, start_date=start_date_str,
      out_dir=FLAGS.fastfeed_dir, out_machine=FLAGS.machine, driver=FLAGS.kline_driver)
  print(kline_cmd)
  completed = subprocess.run(kline_cmd, shell=True, check=True, stdout=subprocess.PIPE)
  output = completed.stdout.decode('utf-8')
  if completed.returncode != 0:
    print(output)
    print(kline_cmd + ' - FAILED')
    sys.exit(1)
  else:
    print('kline generate by trade' + ' - SUCCESS')

  replay_config = FLAGS.merge_driver
  with open(replay_config, 'r') as f:
    json_obj = json.load(f)
    for k, v in json_obj['feed']['exchanges'].items():
      if 'mea' in v.keys():
        des_recipe = os.path.join(FLAGS.fastfeed_dir, FLAGS.machine, trading_date_str,
            v['mea'] + '.' + FLAGS.recipe)
        origin_recipe = os.path.join(FLAGS.fastfeed_dir, FLAGS.machine, trading_date_str,
            v['mea'] + '.' + v['recipe'])
        if not os.path.exists(origin_recipe):
          # copy des_recipe to origin_recipe
          print("mv {} to {}".format(des_recipe, origin_recipe))
          shutil.move(des_recipe, origin_recipe)

  replay_cmd_str = ("bazel-bin/cc/appcoin2/support/feed/fastfeed_replayer "
        "--date={date} --driver={driver} --out-dir={out_dir}")
  replay_cmd = replay_cmd_str.format(date=trading_date_str, driver=FLAGS.merge_driver,
      out_dir=FLAGS.fastfeed_dir)
  print(replay_cmd)
  completed = subprocess.run(replay_cmd, shell=True, check=True, stdout=subprocess.PIPE)
  output = completed.stdout.decode('utf-8')
  if completed.returncode != 0:
    print(output)
    print(replay_cmd + ' - FAILED')
    sys.exit(1)
  else:
    print('kline feed merged to non_tbs' + ' - SUCCESS')


if __name__ == '__main__':
  flags.DEFINE_string('trading_date', None, 'yyyymmdd')
  flags.DEFINE_string('fastfeed_dir', 
      '/remote/iosg/coin-2/buckets/feed.derived.feed_cache.coin',
      'fastfeed root dir')
  flags.DEFINE_string('machine', 'feed-05.ap-northeast-1.aws', 'feed machine')
  flags.DEFINE_string('recipe', 'non_tbs', 'mrege to recipe')
  flags.DEFINE_string('kline_driver',
      'data/coin2/feed/ops/kline-converter/kline_converter.json',
      'kline converter configuration')
  flags.DEFINE_string('merge_driver',
      'data/coin2/feed/ops/kline-converter/kline_non_tbs_merge.json',
      'merge intermediate kline data into non_tbs recipe configuration')

  app.run(main)
